<script setup>
import { ref } from 'vue'
import BaseInput from '../base/BaseInput.vue'
import { sendCode } from '@/api/login'
import useLocale from '@/composables/useLocale'

const props = defineProps({
    email: {
        type: String,
        required: true,
    },
    sendType: {
        type: String,
        default: 'register',
    },
})

const countdown = ref(0)
const { t } = useLocale()

function startCountdown() {
    countdown.value = 60
    const timer = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--
        } else {
            clearInterval(timer)
        }
    }, 1000)
}

async function handleSendCode() {
    if (countdown.value > 0) {
        return
    }
    if (!props.email) {
        uni.showToast({
            title: t('pleaseEnterEmail'),
            icon: 'none',
        })
        return
    }

    startCountdown()
    const resp = await sendCode({
        phoneOrEmail: props.email,
        sendType: 1,
        type: props.sendType,
    })

    if (resp.status === 200) {
        uni.showToast({
            title: t('verificationCodeSent'),
            icon: 'none',
            position: 'top',
        })
    }
}
</script>

<template>
    <BaseInput v-bind="$attrs" type="number">
        <template #suffix>
            <view
                class="ml-3 whitespace-nowrap text-xs text-zinc-950"
                @click="handleSendCode"
            >
                <template v-if="countdown > 0">
                    {{ t('resendAfterSeconds', [countdown]) }}
                </template>
                <template v-else>{{ t('getVerificationCode') }}</template>
            </view>
        </template>
    </BaseInput>
</template>
